package com.leanit.pmc.reg;

import com.leanit.pmc.common.util.VerifyCodeUtils;
import com.leanit.pmc.reg.bean.RegMail;
import com.leanit.pmc.reg.service.RegService;
import freemarker.template.TemplateException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 用户登录controller
 *
 * @author
 */
@Controller
@RequestMapping("/reg")
public class RegController {


    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    RegService regService;

    /**
     * 注册的1step 填写邮箱
     *
     * @return
     */
    @RequestMapping(value = "/stepOne", method = {RequestMethod.GET, RequestMethod.HEAD})
    public String stepOne() {
        return "reg/step_one";
    }

    /**
     * 注册的1step 填写邮箱
     *
     * @return
     */
    @RequestMapping(value = "/stepTwo", method = {RequestMethod.GET, RequestMethod.HEAD})
    public String validMail(String mailKey, ModelMap modelMap) {
        RegMail regMail = regService.getRegMail(mailKey);
        if (null == regMail || !regService.validMailKey(regMail.getMail(), regMail.getMailKey())) {
            return "reg/invalid_mail";
        }
        modelMap.put("regMail", regMail);
        return "reg/step_two";
    }

    /**
     * 注册的1step 填写邮箱
     *
     * @return
     */
    @RequestMapping(value = "/validMail", method = {RequestMethod.GET, RequestMethod.HEAD})
    public String validMail(String mail, String mailKey, ModelMap modelMap) {
        modelMap.put("mail", mail);
        modelMap.put("mailKey", mailKey);
        return "reg/valid_mail";
    }

    /**
     * 验证邮箱
     *
     * @param session
     * @param mail
     * @param code
     * @return
     */
    @RequestMapping(value = "/verifyMail", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/text; charset=utf-8")
    @ResponseBody
    public String verifyMail(HttpSession session, String mail, String code, String mailKey) throws IOException, TemplateException {
        if (VerifyCodeUtils.verifyCode(session, code)) {
            return regService.sendMail(mail);
        } else if (StringUtils.isNotEmpty(mailKey)) {
            return regService.sendMail(mail, mailKey);
        }
        return "验证码输入错误，请重新输入";
    }

}
